package com.bestcem.xm.member.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.bestcem.xm.common.core.constant.AppRequestErrorCode;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import com.bestcem.xm.label.grpc.service.param.label.ListLabelValuesParam;
import com.bestcem.xm.label.service.LabelValueService;
import com.bestcem.xm.label.service.dto.label.LabelValueDTO;
import com.bestcem.xm.member.controller.vo.filter.GetTagInfoChoice;
import com.bestcem.xm.member.controller.vo.filter.GetTagInfoVO;
import com.bestcem.xm.member.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;

import static com.bestcem.xm.member.constant.Constants.M_FIELD_ATTRIBUTE_MAP;

/**
 * 示例服务
 *
 * @author yf.wang <yf.wang@idiaoyan.com>
 * @version V1.0
 * @date 2021/8/4
 */
@Slf4j
@RestController
@RequestMapping("/member/filter")
public class FilterController {

    @Resource
    private MemberService memberService;

    @Resource
    private LabelValueService labelValueService;

    /**
     * 获取计算信息
     *
     * @return
     */
    @GetMapping("/compute_info")
    public XmResultJson getComputeInfo() {
        return memberService.listComputeFields();
    }

    @GetMapping("/base_info")
    public XmResultJson getBaseInfo(@RequestParam("attribute") Integer mtype,
                                    HttpServletRequest request) {
        if (!M_FIELD_ATTRIBUTE_MAP.containsKey(mtype)) {
            return XmResultJson.fail(AppRequestErrorCode.PARAM_RANGE, "not found");
        }

        
        String orgId = SecurityContextHolder.getOrgId();
        
         String userId = SecurityContextHolder.getUserId();
        if (log.isInfoEnabled()) {
            log.info("orgId: {}", orgId);
            log.info("userId: {}", userId);
        }
        return memberService.listMetaFields(mtype, orgId);
    }

    /**
     * 返回标签信息过滤参数
     *
     * <pre>
     * 返回值:
     * {
     *     "code": 0,
     *     "data": [{
     *         "field": "labels",
     *         "tag_id": "60d801aeaace700009a64481",
     *         "display_name": "\u6807\u7b7e1", // 标签1
     *         "type": "select",
     *         "source": "label",
     *         "choice": [{
     *             "id": "60d801aeaace700009a64482",
     *             "value": "test\u9ad8",  // test高
     *             "serial": 0
     *         }]
     *     }, {
     *         "field": "labels",
     *         "tag_id": "60c888ad10c377f5f135e86c",
     *         "display_name": "\u7b54\u9898\u5b8c\u6210\u7387", // 答题完成率
     *         "type": "select",
     *         "source": "label",
     *         "choice": [{
     *             "id": "60c888ad10c377f5f135e88e",
     *             "value": "\u4f4e",
     *             "serial": 2
     *         }, {
     *             "id": "60c888ad10c377f5f135e883",
     *             "value": "\u4e2d",
     *             "serial": 1
     *         }, {
     *             "id": "60c888ad10c377f5f135e87a",
     *             "value": "\u9ad8",
     *             "serial": 0
     *         }]
     *     }]
     * }
     * <pre/>
     *
     * @param attribute 标签的属性，归属于哪种联系人
     * @return List[GetTagInfoVO]
     * @author zh.zhang <zh.zhang@idiaoyan.com>
     * @date 2021-08-20
     */
    @GetMapping("/tag_info")
    public XmResultJson getTagInfo(@RequestParam(value = "attribute", required = false)
                                               Integer attribute,
                                       HttpServletRequest request) {
        String orgId = SecurityContextHolder.getOrgId();
        
         String userId = SecurityContextHolder.getUserId();
        if (log.isInfoEnabled()) {
            log.info("orgId: {}", orgId);
            log.info("userId: {}", userId);
        }
        if (ObjectUtil.isNull(attribute)) {
            // 默认: 个人联系人
            attribute = 0;
        }

        // 标签值param
        ListLabelValuesParam listLabelValuesParam = new ListLabelValuesParam();
        listLabelValuesParam.setOrgId(orgId);
        listLabelValuesParam.setAttribute(attribute);
        listLabelValuesParam.setIds(null);
        // 获取标签值的相关信息
        ServiceResult<List<LabelValueDTO>> result = labelValueService.listLabelValues(listLabelValuesParam);

        if (result.isSuccess()) {
            List<LabelValueDTO> labelValueDtos = result.getData();

            if (CollectionUtil.isNotEmpty(labelValueDtos)) {
                // 处理 标签信息过滤参数
                // map<labelName, GetTagInfoVO>
                LinkedHashMap<String, GetTagInfoVO> map = makeTagInfo(labelValueDtos);
                return XmResultJson.success(map.values());
            } else {
                return XmResultJson.success(Collections.EMPTY_LIST);
            }

        } else {
            return XmResultJson.fail(-1, result.getMsg());
        }
    }

    /**
     * 处理 标签信息过滤参数
     *
     * @param labelValueDtos LabelValueDTOs
     * @return LinkedHashMap{String, GetTagInfoVO}
     * @author zh.zhang <zh.zhang@idiaoyan.com>
     * @date 2021-08-20
     */
    private LinkedHashMap<String, GetTagInfoVO> makeTagInfo(List<LabelValueDTO> labelValueDtos) {
        // <labelName, GetTagInfoVO>
        LinkedHashMap<String, GetTagInfoVO> map = new LinkedHashMap<>();

        // 处理 标签信息过滤参数
        for (LabelValueDTO labelValueDTO : labelValueDtos) {
            // 1.labelName
            String labelName = labelValueDTO.getLabelName();

            // 2.GetTagInfoVO
            if (StrUtil.isNotBlank(labelName)) {
                if (!map.containsKey(labelName)) {
                    // map中未有labelName，新建GetTagInfoVO、GetTagInfoChoice
                    GetTagInfoVO vo = new GetTagInfoVO();
                    vo.setField("labels");
                    vo.setTagId(labelValueDTO.getLabelId());
                    vo.setDisplayName(labelName);
                    vo.setType("select");
                    vo.setSource("label");

                    // choice: 标签值信息
                    ArrayList<GetTagInfoChoice> choices = new ArrayList<>();
                    GetTagInfoChoice choice = new GetTagInfoChoice();
                    choice.setId(labelValueDTO.getId());
                    choice.setValue(labelValueDTO.getValue());
                    choice.setSerial(labelValueDTO.getSerial());
                    choices.add(choice);
                    vo.setChoices(choices);

                    map.put(labelName, vo);
                } else {
                    // map中已有labelName，添加GetTagInfoChoice
                    GetTagInfoVO vo = map.get(labelName);
                    List<GetTagInfoChoice> choices = vo.getChoices();

                    // choice: 标签值信息
                    GetTagInfoChoice choice = new GetTagInfoChoice();
                    choice.setId(labelValueDTO.getId());
                    choice.setValue(labelValueDTO.getValue());
                    choice.setSerial(labelValueDTO.getSerial());
                    choices.add(choice);
                }
            }
        }

        return map;
    }

}
